# arg 1:  the new package version
# arg 2:  the old package version

KERNEL_NAME=
KERNEL_VERSION=

initramfsfname="initramfs-linux${KERNEL_NAME}.img"
initramfs="/boot/${initramfsfname}"
vmlinuz="/boot/vmlinuz-linux${KERNEL_NAME}"

prepend_microcode () {
  echo "prepending CPU microcode to ${initramfs}"
  local destfirst="/tmp/initrd/"
  local destmc="${destfirst}/kernel/x86/microcode/"
#  mkdir -p "${destmc}"
	install -dm644 "${destmc}"
  ( cp -f "/lib/firmware/amd-ucode/microcode_amd.bin" "${destmc}/AuthenticAMD.bin" && cd "${destfirst}" && find . | cpio -o -H newc > "../ucode.cpio" 2>/dev/null && cd .. && cat "ucode.cpio" "${initramfs}" > "/tmp/${initramfsfname}" && mv -f "/tmp/${initramfsfname}" "${initramfs}")
	local ec=$?
	if [[ $ec -eq 0 ]]; then
		echo "success."
	else
		#TODO: make errors be red so it's more obvious
		echo "failed!"
	fi
	return $ec
}

rebuild_fglrx () {
  #
	#note to self, I don't need catalyst-hook.service so: sudo systemctl disable catalyst-hook
	# this exe is installed by catalyst-hook package
	cbmexe="$(which catalyst_build_module)"
  echo "cbmexe=$cbmexe"
	if [ -n "$cbmexe" ] && [ -x "${cbmexe}" ]; then
		echo "recompiling fglrx module for ${KERNEL_VERSION} :"
		${cbmexe} ${KERNEL_VERSION}
		local ec=$?
		if [[ $ec -eq 0 ]]; then
			echo "success."
		else
			#TODO: make errors be red so it's more obvious
			echo "failed!"
		fi
		return $ec
  else
    echo "skipping fglrx due to not installed"
	fi
}

run_dkms() {
	# $1 = autoinstall or uninstall  operation to be passed to dkms
	local oper="$1"
	if [ -z "$oper" ]; then
		echo "call failed for function: $FUNCNAME you didn't specify an operation"
		return 1
	fi
	#TODO: check for valid $oper values
	# for the cases when dkms isn't patched to auto rebuild when kernel compile.h changes
	# and/or for the cases when systemd-modules-load.service loads existing modules before dkms gets the chance to rebuild them (quite possibly 'causing an oops, for the case when rebuilt kernel with debugging locks for example) which is still the case on my manjaro dist
	dkmsexe=$(which dkms)
	if [ ! -x "$dkmsexe" ]; then
		echo -n "failed to find dkms executable, "
		if pacman -Qq dkms; then
			#TODO: make errors be red color
			echo "aborting"
			exit 33
		else
			echo "ignoring because you don't have the package installed"
		fi		
	else
    echo "running dkms: ${dkmsexe} ${oper} -k \"$KERNEL_VERSION\""
		${dkmsexe} ${oper} -k "$KERNEL_VERSION"
		local ec=$?
		#too bad it doesn't return non-zero when failed to build/install
		if [[ $ec -eq 0 ]]; then
			echo "good."
		else
			#TODO: make red
			echo "bad."
		fi
    return $ec #return it anyways
	fi
}

update_grub () {
  # update grub.cfg
  if [ -f /usr/sbin/update-grub ]; then
      update-grub
  else
      echo "WARNING: It seems that grub is not installed - Your system might not boot."
      echo "Add followed initramfs files to your bootloader config:"
      echo ">> linux	${vmlinuz}"
      echo ">> initrd	${initramfs}"
  fi
}



post_install () {
  # updating module dependencies
  echo ">>> Updating module dependencies. Please wait ..."
  depmod ${KERNEL_VERSION}
  echo ">>> Generating initial ramdisk, using mkinitcpio.  Please wait..."
  mkinitcpio -p linux${KERNEL_NAME}

  echo ">>> WARNING: AT keyboard support is no longer built into the kernel."
  echo ">>>          In order to use your keyboard during early init, you MUST"
  echo ">>>          include the 'keyboard' hook in your mkinitcpio.conf."

	prepend_microcode
	update_grub  
	rebuild_fglrx
	run_dkms autoinstall
}

post_upgrade() {
  if findmnt --fstab -uno SOURCE /boot &>/dev/null && ! mountpoint -q /boot; then
    echo "WARNING: /boot appears to be a separate partition but is not mounted."
  fi

  # updating module dependencies
  echo ">>> Updating module dependencies. Please wait ..."
  depmod ${KERNEL_VERSION}
  echo ">>> Generating initial ramdisk, using mkinitcpio.  Please wait..."
  mkinitcpio -p linux${KERNEL_NAME}

  if [ $(vercmp $2 3.13) -lt 0 ]; then
    echo ">>> WARNING: AT keyboard support is no longer built into the kernel."
    echo ">>>          In order to use your keyboard during early init, you MUST"
    echo ">>>          include the 'keyboard' hook in your mkinitcpio.conf."
  fi

	prepend_microcode
	update_grub  
	rebuild_fglrx
	run_dkms autoinstall
}

post_remove() {
	# avoid leaving /usr/lib/modules/kernelnamehere/*.ko modules around from dkms
	# TODO: make autouninstall option for dkms because we need it to remove all dkms modules for this kernel and we cannot possibly know which of them are installed.
	run_dkms autouninstall
  # also remove the compat symlinks
	#FIXME: not sure what's with these, they are the same files in our current case (linux-git package)
  rm -f boot/initramfs-linux${KERNEL_NAME}.img
  rm -f boot/initramfs-linux${KERNEL_NAME}-fallback.img

	update_grub  
	#TODO: run dkms uninstall ${KERNEL_VERSION}
}

